﻿using Contact.API.Data.Core;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Contact.API.Data
{
    public class ContactContext
    {
        private readonly IMongoDatabase _mongoDatabase;
        private readonly IMongoCollection<ContactBook> _mongoCollection;
        private readonly AppSettings _appSettings;
        public ContactContext(IOptionsSnapshot<AppSettings> optionsSnapshot)
        {
            _appSettings = optionsSnapshot.Value;
            var client = new MongoClient(_appSettings.MongoContactConnectionString);
            if (client!=null)
            {
                _mongoDatabase = client.GetDatabase(_appSettings.MongoContactDatabaseName);
            }
        }

        private void CheckAndCreateColleaction(string name)
        {
            //var collections = _mongoDatabase.ListCollections().ToList();
            //var names =new  List<string>();
            //collections.ForEach(c =>
            //{
            //    names.Add(c["name"].AsString);
            //});
            var names = _mongoDatabase.ListCollections().ToList().Select(c => c["name"].AsString);
            if (!names.Contains(name))
            {
                _mongoDatabase.CreateCollection(name);
            }
        }
        public IMongoCollection<ContactBook> Contactbooks
        {
            get
            {
                CheckAndCreateColleaction("Contactbook");
                return _mongoDatabase.GetCollection<ContactBook>("Contactbook");
            }
        }
        public IMongoCollection<ContactApplyRequest> ContactApplyRequests
        {
            get
            {
                CheckAndCreateColleaction("ContactApplyRequest");
                return _mongoDatabase.GetCollection<ContactApplyRequest>("ContactApplyRequest");
            }
        }
    }
}
